package com.soyea.controller;

import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import javax.servlet.http.HttpSession;

/**
 * 跳转controller
 * Created by skh on 2018/1/24
 */
@Controller
@Slf4j
public class ViewController {

	@Autowired
	private WxMpService wxMpService;

	//跳转页面
	@RequestMapping("/{url}.html")
	public String toIndex(@PathVariable String url){
		return url;
	}

	//授权接口 返回code
	@RequestMapping("/oauth")
	public ModelAndView oauth2build(String code, HttpSession session) {
		log.info("授权回调成功");
		log.info("获取到的code:{}", code);

		//去获取access_token
		WxMpOAuth2AccessToken accessToken = null;
		try {
			accessToken = wxMpService.oauth2getAccessToken(code);
			log.info("[授权] 获取AccessToken成功,AccessToken={}", accessToken);

			//判断openId是否为空,如果为空,需要重新授权
			log.info("[授权] 获取到的openId={}", accessToken.getOpenId());

			if (StringUtils.isBlank(accessToken.getOpenId())) {
				ModelAndView modelAndView = new ModelAndView("signError");
				return modelAndView;
			}

			//授权成功,跳转到签到页面
			ModelAndView modelAndView = new ModelAndView("PhoneSign");
			modelAndView.addObject("openid", accessToken.getOpenId());
			session.setAttribute("openid", accessToken.getOpenId());
			return modelAndView;

		} catch (WxErrorException e) {
			//获取AccessToken出错
			log.error("获取AccessToken出错", e);
			ModelAndView modelAndView = new ModelAndView("signError");
			return modelAndView;
		}
	}

}
